package jp.co.nes.awssupport.common.utility;

import com.amazonaws.ClientConfiguration;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.sns.AmazonSNS;
import com.amazonaws.services.sns.AmazonSNSClientBuilder;
import com.amazonaws.services.sns.model.PublishRequest;
import com.amazonaws.services.sns.model.PublishResult;

import jp.co.nes.awssupport.common.bean.BaseBean;

/**
 * SNSヘルパーです。<br>
 * SNSに関する機能を提供します。
 */
public class AwsSnsHelper extends AwsHelperBase {

    /** クライアント */
    private AmazonSNS client;

    /**
     * デフォルトコンストラクタです。
     */
    public AwsSnsHelper() {
    }

    /*
     * (非 Javadoc)
     * @see jp.co.nes.awssupport.common.utility.AwsHelperBase#init(com.amazonaws.regions.Regions, com.amazonaws.auth.AWSCredentials, com.amazonaws.ClientConfiguration)
     */
    @Override
    protected void init(Regions regions, AWSCredentials credentials, ClientConfiguration config) {
        boolean isLocalTest = Boolean.valueOf(PropertiesUtil.getProperty("LocalTest", "false"));
        if (!isLocalTest) {
            if (credentials == null) {
                if (config == null) {
                    client = AmazonSNSClientBuilder.standard()
                            .withRegion(regions)
                            .build();
                } else {
                    client = AmazonSNSClientBuilder.standard()
                            .withRegion(regions)
                            .withClientConfiguration(config)
                            .build();
                }
            } else {
                if (config == null) {
                    client = AmazonSNSClientBuilder.standard()
                            .withRegion(getRegions())
                            .withCredentials(new AWSStaticCredentialsProvider(credentials))
                            .withClientConfiguration(new ClientConfiguration())
                            .build();
                } else {
                    client = AmazonSNSClientBuilder.standard()
                            .withRegion(getRegions())
                            .withCredentials(new AWSStaticCredentialsProvider(credentials))
                            .withClientConfiguration(config)
                            .build();
                }
            }
        }
    }

    /**
     * トピックを送信します。
     *
     * @param topicArn トピックのarn
     * @param bean 送信内容(json形式に変換して送信します)
     * @return 送信結果
     */
    public <T extends BaseBean> PublishResult publish(String topicArn, T bean) {
        String message = JsonUtil.convertBeanToJsonString(bean);
        PublishRequest publishRequest = new PublishRequest(topicArn, message);
        return client.publish(publishRequest);
    }
}
